package com.gjintel.framework.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.SocketException;

import org.apache.log4j.Logger;

import com.gjintel.framework.log.model.LogInfo;
import com.gjintel.framework.log.util.LogUtil;
import com.gjintel.framework.log.util.LogUtil.LogType;

public class SocketUtil  {
	private static final Logger LOG = Logger.getLogger(SocketUtil.class);
	public static String socketPost(String postStr,String url,int port) throws IOException, SocketException{
		Socket socket;
//		try {
		socket = new Socket(url,port);  	//1. connect server
		//2.get  socket IO stream
		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(  
                socket.getOutputStream(), "gbk"));
		writer.write(postStr);
		writer.flush();
        InputStream is=socket.getInputStream();
        BufferedReader br=new BufferedReader(new InputStreamReader(is,"gbk"));

        //3.operation socket,handle IO,return   
        socket.shutdownOutput(); 
        StringBuffer _sb=new StringBuffer();
        String reply=null;  
        while(!((reply=br.readLine())==null)){
            _sb.append(reply);
        }
        
        LOG.debug("返回的数据是："+_sb.toString());
        //4.关闭资源  
        br.close();
        is.close();
        writer.close();  
        socket.close();
        
        //加入日志
        //记住修改log表的content为varchar(2000)
        LogInfo log1= new LogInfo("发送的数据："+postStr+"|||接收的数据"+_sb.toString(),"","",
        		String.valueOf(LogType.ADD.ordinal()), "SocketUtil.class", "");
       // LogUtil.addLog(log1);
        System.out.println("发送的数据："+postStr+"|||接收的数据"+_sb.toString());
        
        return _sb.toString();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//			return "";
//		}
	}
}